package com.example.tableapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.example.tableapplication.JavaBean.ArrivalVouch;
import com.example.tableapplication.JavaBean.ArrivalVouchs;
import com.example.tableapplication.application.MyApplication;
import com.example.tableapplication.dao.SOAPUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import cn.bertsir.zbar.Qr.ScanResult;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import cn.bertsir.zbar.view.ScanLineView;

public class MainActivity_2 extends AppCompatActivity {
    public MyApplication myApplication;
    public static TableAdapter tableAdapter;
    public static String[] HeadTitle={"单据号","日期","业务员","供应商","部门","制单人"};
    public static String[] BodyTitle={"存货编码","存货名称","规格型号","主计量","数量"};
    public static int headlen=HeadTitle.length+1;
    public static int bodylen=BodyTitle.length+1;
    public String scan_result="";
    private EditText editText;
    private static final String TAG = "MainActivity_1";
    private ImageView iv_qr;
    private EditText et_qr_content;
    private EditText et_qr_title;
    private EditText et_qr_des;
    private CheckBox cb_show_title;
    private CheckBox cd_show_des;
    private CheckBox cb_show_ding;
    private CheckBox cb_show_custom_ding;
    private CheckBox cb_show_flash;
    private CheckBox cb_show_album;
    private CheckBox cb_only_center;
    private CheckBox cb_create_add_water;
    private CheckBox cb_crop_image;
    private CheckBox cb_show_zoom;
    private CheckBox cb_auto_zoom;
    private CheckBox cb_finger_zoom;
    private CheckBox cb_double_engine;
    private CheckBox cb_loop_scan;
    private CheckBox cb_auto_light;
    private CheckBox cb_have_vibrator;
    private RadioButton rb_qrcode;
    private RadioButton rb_bcode;
    private RadioButton rb_all;
    private RadioButton rb_screen_sx;
    private RadioButton rb_screen_hx;
    private RadioButton rb_screen_auto;
    private EditText et_loop_scan_time;
    private RadioButton rb_scanline_radar;
    private RadioButton rb_scanline_grid;
    private RadioButton rb_scanline_hybrid;
    private RadioButton rb_scanline_line;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_2);
        myApplication = (MyApplication) getApplication();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

//        initView1();
        initData();

        Log.e("activityState","SecondActivity_onCreate");
    }

    //获取存储到全局变量类中的扫描设置界面各个控件的状态
    public void initView1(){

//        iv_qr = myApplication.getIv_qr();
        et_qr_content.setText(myApplication.getEt_qr_content());
        et_qr_title.setText(myApplication.getEt_qr_title());
        et_qr_des.setText(myApplication.getEt_qr_des());
        cb_show_title.setChecked(Boolean.parseBoolean(myApplication.getCb_show_title()));
        cd_show_des.setChecked(Boolean.parseBoolean(myApplication.getCd_show_des()));
        cb_show_ding.setChecked(Boolean.parseBoolean(myApplication.getCb_show_ding()));
        cb_show_custom_ding.setChecked(Boolean.parseBoolean(myApplication.getCb_show_custom_ding()));
        cb_show_flash.setChecked(Boolean.parseBoolean(myApplication.getCb_show_flash()));
        cb_show_album.setChecked(Boolean.parseBoolean(myApplication.getCb_show_album()));
        cb_only_center.setChecked( Boolean.parseBoolean(myApplication.getCb_only_center()));
        cb_create_add_water.setChecked(Boolean.parseBoolean(myApplication.getCb_create_add_water()));
        cb_crop_image.setChecked(Boolean.parseBoolean(myApplication.getCb_crop_image()));
        cb_show_zoom.setChecked(Boolean.parseBoolean(myApplication.getCb_show_zoom()));
        cb_auto_zoom.setChecked(Boolean.parseBoolean(myApplication.getCb_auto_zoom()));
        cb_finger_zoom.setChecked(Boolean.parseBoolean(myApplication.getCb_finger_zoom()));
        cb_double_engine.setChecked(Boolean.parseBoolean(myApplication.getCb_double_engine()));
        cb_loop_scan.setChecked(Boolean.parseBoolean(myApplication.getCb_loop_scan()));
        cb_auto_light.setChecked(Boolean.parseBoolean(myApplication.getCb_auto_light()));
        cb_have_vibrator.setChecked(Boolean.parseBoolean(myApplication.getCb_have_vibrator()));
        rb_qrcode.setChecked(Boolean.parseBoolean(myApplication.getRb_qrcode()));
        rb_bcode.setChecked(Boolean.parseBoolean(myApplication.getRb_bcode()));
        rb_all.setChecked( Boolean.parseBoolean(myApplication.getRb_all()));
        rb_screen_sx.setChecked(Boolean.parseBoolean(myApplication.getRb_screen_sx()));
        rb_screen_hx.setChecked(Boolean.parseBoolean(myApplication.getRb_screen_hx()));
        rb_screen_auto.setChecked(Boolean.parseBoolean(myApplication.getRb_screen_auto()));
        et_loop_scan_time.setText(myApplication.getEt_loop_scan_time());
        rb_scanline_radar.setChecked(Boolean.parseBoolean(myApplication.getRb_scanline_radar()));
        rb_scanline_grid.setChecked(Boolean.parseBoolean(myApplication.getRb_scanline_grid()));
        rb_scanline_hybrid.setChecked(Boolean.parseBoolean(myApplication.getRb_scanline_hybrid()));
        rb_scanline_line.setChecked(Boolean.parseBoolean(myApplication.getRb_scanline_line()));
//        cb_show_title.setSelected(false);
//        System.out.println(cb_show_title.isChecked());
//        cb_show_title.setSelected(true);
//        System.out.println(cb_show_title.isChecked());
    }

    //获取扫描设置初始化界面各控件的状态
    public  void initView2(){
        //用LayoutInflater加载布局
        LayoutInflater factory = LayoutInflater.from(MainActivity_2.this);

        //获取dialog布局文件获取View
        final View textEntryView = factory.inflate(R.layout.activity_main_1, null);

        // 通过textEntryView来获取控件
//        final Button bt_scan = textEntryView.findViewById(R.id.bt_scan);
//        final String TAG = "MainActivity_1";
//        final ImageView iv_qr = textEntryView.findViewById(R.id.iv_qr);
//        final Button bt_make = textEntryView.findViewById(R.id.bt_make);
        et_qr_content = textEntryView.findViewById(R.id.et_qr_content);
        et_qr_title = textEntryView.findViewById(R.id.et_qr_title);
        et_qr_des = textEntryView.findViewById(R.id.et_qr_des);
        cb_show_title = textEntryView.findViewById(R.id.cb_show_title);
        cd_show_des = textEntryView.findViewById(R.id.cd_show_des);
        cb_show_ding = textEntryView.findViewById(R.id.cb_show_ding);
        cb_show_custom_ding = textEntryView.findViewById(R.id.cb_show_custom_ding);
        cb_show_flash = textEntryView.findViewById(R.id.cb_show_flash);
        cb_show_album = textEntryView.findViewById(R.id.cb_show_album);
        cb_only_center = textEntryView.findViewById(R.id.cb_only_center);
        cb_create_add_water = textEntryView.findViewById(R.id.cb_create_add_water);
        cb_crop_image = textEntryView.findViewById(R.id.cb_crop_image);
        cb_show_zoom = textEntryView.findViewById(R.id.cb_show_zoom);
        cb_auto_zoom = textEntryView.findViewById(R.id.cb_auto_zoom);
        cb_finger_zoom = textEntryView.findViewById(R.id.cb_finger_zoom);
        cb_double_engine = textEntryView.findViewById(R.id.cb_double_engine);
        cb_loop_scan = textEntryView.findViewById(R.id.cb_loop_scan);
        cb_auto_light = textEntryView.findViewById(R.id.cb_auto_light);
        cb_have_vibrator = textEntryView.findViewById(R.id.cb_have_vibrator);
        rb_qrcode = textEntryView.findViewById(R.id.rb_qrcode);
        rb_bcode = textEntryView.findViewById(R.id.rb_bcode);
        rb_all = textEntryView.findViewById(R.id.rb_all);
        rb_screen_sx = textEntryView.findViewById(R.id.rb_screen_sx);
        rb_screen_hx = textEntryView.findViewById(R.id.rb_screen_hx);
        rb_screen_auto = textEntryView.findViewById(R.id.rb_screen_auto);
        et_loop_scan_time = textEntryView.findViewById(R.id.et_loop_scan_time);
        rb_scanline_radar = textEntryView.findViewById(R.id.rb_scanline_radar);
        rb_scanline_grid = textEntryView.findViewById(R.id.rb_scanline_grid);
        rb_scanline_hybrid = textEntryView.findViewById(R.id.rb_scanline_hybrid);
        rb_scanline_line = textEntryView.findViewById(R.id.rb_scanline_line);

//        final TextView tv1 = (TextView) textEntryView.findViewById(R.id.textView1);

        //        Toast.makeText(MainActivity.this, tv1.getText(),
//
//                Toast.LENGTH_SHORT).show();
    }


    //扫描后加载数据
    public void initData(){
        for (int i = 0; i <TableAdapter.checkBoxes.size(); i++) {      //复选框的个数为：count=行总数/8，创建count个复选框设置初始勾选状态为false
            TableAdapter.checkBoxes.get(i).setEnabled(true);
            TableAdapter.checkBoxes.get(i).setChecked(false);
        }
        String s;
//        LinkedHashMap paramh=new LinkedHashMap ();
//        LinkedHashMap  paramb=new LinkedHashMap ();
        List<ArrivalVouch> resulth = null;
        List<ArrivalVouchs> resultb = null;
//        result=new DbUtils().QureySql();      //连接数据库查询数据
        editText=findViewById(R.id.result_scan);

        //判断是否已扫描，扫面之后才会显示数据
        if(!(editText.getText().toString().equals("")||editText.getText().toString().equals(null)||editText.getText().length()==0)){
            String str[]=getsplitString(scan_result.trim(),"\\|\\||\\|");
            if(str.length==3){
                JsonObject jsonh=new JsonObject();
                JsonObject jsonb=new JsonObject();
                String cCode=str[2];
                //获取表头数据
                jsonh.addProperty("cCode",cCode);
//                paramh.put("cCode",cCode);
                s=connect("getArrivalVouch_proc",jsonh);
                Gson gsonh = new Gson();
                resulth=gsonh.fromJson(s, new TypeToken<List<ArrivalVouch>>(){}.getType());
                //获取所有表体数据
                jsonb.addProperty("TYPE","1");
                jsonb.addProperty("cCode",cCode);
                jsonb.addProperty("rowno","0");
//                paramb.put("TYPE","1");
//                paramb.put("cCode",cCode);
//                paramb.put("rowno","0");
                s=connect("getArrivalVouchs_proc",jsonb);
                Gson gsonb = new Gson();
                resultb=gsonb.fromJson(s, new TypeToken<List<ArrivalVouchs>>(){}.getType());

            }else if(str.length==4){
                String cCode=str[2];
                String rowno=str[3];
                JsonObject jsonh=new JsonObject();
                JsonObject jsonb=new JsonObject();
                //获取表头数据
                jsonh.addProperty("cCode",cCode);
//                paramh.put("cCode",cCode);
                s=connect("getArrivalVouch_proc",jsonh);
                Gson gsonh = new Gson();
                resulth=gsonh.fromJson(s, new TypeToken<List<ArrivalVouch>>(){}.getType());
                //获取表体数据
                jsonb.addProperty("TYPE","2");
                jsonb.addProperty("cCode",cCode);
                jsonb.addProperty("rowno",rowno);
//                paramb.put("TYPE","2");
//                paramb.put("cCode",cCode);
//                paramb.put("rowno",rowno);
                s=connect("getArrivalVouchs_proc",jsonb);
                Gson gsonb = new Gson();
                resultb=gsonb.fromJson(s, new TypeToken<List<ArrivalVouchs>>(){}.getType());
            }

//            result=new DbUtils().QureySql();      //连接数据库查询数据
        }
        List<TableRow> table = new ArrayList<TableRow>() {};//声明为全局变量，供之后单条记录使用
        ListView list_process_storage1=(ListView)findViewById(R.id.listview1);
        Button btn_scan=(Button) findViewById(R.id.btn_scan);  //扫描按钮
        WindowManager wm1 = this.getWindowManager();
        int width1 = wm1.getDefaultDisplay().getWidth()/2;   //得到屏幕的宽度
        int height1 = wm1.getDefaultDisplay().getHeight();   //得到屏幕的高度

        int i=0;
//        if(result!=null){
            //表头
//            String[] columnHead1 = HeadTitle;
//            String[] columnKey1={"","","","","","","","",""};
//            List<TableRow> table2;//声明为全局变量，供之后单条记录使用
//            table2 = TableUtil.addSingleRecord(width1, this,"表头信息" ,"单据号",columnKey1, columnHead1);
//            table.addAll(table2);

            //表头
            if(resulth!=null&&resultb!=null){
            for (ArrivalVouch av : resulth) {
                String[] columnHead = HeadTitle;
                String[] columnKey = {av.getcCode(), av.getdDate(), av.getcPsn_Name(), av.getcVenName(), av.getcDepName(), av.getcMaker()};
                List<TableRow> table2;//声明为全局变量，供之后单条记录使用
                table2 = TableUtil.addSingleRecord(width1, this, "表头信息", av.getcCode(), columnKey, columnHead);
                table.addAll(table2);
            }
            //表体
            for (ArrivalVouchs avs : resultb) {
                String[] columnHead = BodyTitle;
                String[] columnKey={avs.getcInvCode(),avs.getcInvName(),avs.getcInvStd(),avs.getcComUnitCode(),avs.getiQuantity()};
                List<TableRow> table1;//声明为全局变量，供之后单条记录使用
                table1 = TableUtil.addSingleRecord(width1, this,"第"+(++i)+"行" ,avs.getIvouchrowno(),columnKey, columnHead);
                table.addAll(table1);
            }
        }

        tableAdapter = new TableAdapter(this, table);
        list_process_storage1.setAdapter(tableAdapter);
        Button btn_sub=findViewById(R.id.baojian);
        btn_sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                StringBuffer sb=new StringBuffer();
//                //拿到所有的子类长度
//                int cNum = Linear.getChildCount();
//                for (int i = 0; i < cNum; i++) {
//                    //根据i 拿到每一个CheckBox
//                    CheckBox cb= (CheckBox) Linear.getChildAt(i);
//                    //判断CheckBox是否被选中
//                    if(cb.isChecked()){
//                        //把被选中的文字添加到StringBuffer中
//                        sb.append(cb.getText().toString());
//                    }
//                }
                Toast.makeText(MainActivity_2.this, TableRowView.selectedStrings.toString(), Toast.LENGTH_SHORT).show();
            }
        });

        btn_scan.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                start();
            }
        });
//            String[] columnHead={"第一行","第二行","第三行"  };
//            String[] columnKey={"1","2","3"};

////        list_process_storage.setOnItemClickListener(new ItemClickEvent());
    }


    public String connect(String method, JsonObject json){
        //服务器地址
        String dbip=myApplication.getEt_dbadress();
        String dbport=myApplication.getEt_dbport();
        String dbname=myApplication.getEt_dbname();
        String dbusername=myApplication.getEt_dbusername();
        String dbpassword=myApplication.getEt_dbpassword();
        String wsdUrl="http://"+dbip+":9090/ConnectToU8/services/TableInfoService?wsdl";
        //方法名
//        String method1=method;
//        HashMap param1=new HashMap();
//        param1.put("dbip",dbip);
//        param1.put("dbport",dbport);
//        param1.put("dbname",dbname);
//        param1.put("dbusername",dbusername);
//        param1.put("dbpassword",dbpassword);

//        JsonObject json =new JsonObject();
        json.addProperty("dbip",dbip);
        json.addProperty("dbport",dbport);
        json.addProperty("dbname",dbname);
        json.addProperty("dbusername",dbusername);
        json.addProperty("dbpassword",dbpassword);
        Object result= SOAPUtil.doTransport(wsdUrl, method,json.toString());
//        JSONArray jsonArray = null;
//        try {
//            jsonArray = new JSONArray(result.toString().trim());
//            if(jsonArray.length() > 0){
//                for (int i = 0; i < jsonArray.length(); i++) {
//                    JSONObject jsonObject = null;
//                    jsonObject = jsonArray.getJSONObject(i);
//                    System.out.println("遍历jsonArray,获取数组中的name属性值："+jsonObject.get("xingming"));
//                }
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
            return result.toString();
//        results.setText(result.toString());
    }

    private void start() {
        //判断扫描设置是否被修改过：若修改过则获取修改后存储到MyApplication中的空间状态，若没修改过获取扫描设置界面各控件初始化状态
        if(myApplication.getMyState()){
            initView2();
            initView1();
        }else{
            initView2();
        }


        int scan_type = 0;
        int scan_view_type = 0;
        int screen = 1;
        int line_style = ScanLineView.style_radar;
        if (rb_all.isChecked()) {
            scan_type = QrConfig.TYPE_ALL;
            scan_view_type = QrConfig.SCANVIEW_TYPE_QRCODE;
        } else if (rb_qrcode.isChecked()) {
            scan_type = QrConfig.TYPE_QRCODE;
            scan_view_type = QrConfig.SCANVIEW_TYPE_QRCODE;
        } else if (rb_bcode.isChecked()) {
            scan_type = QrConfig.TYPE_BARCODE;
            scan_view_type = QrConfig.SCANVIEW_TYPE_BARCODE;
        }
        if (rb_screen_auto.isChecked()) {
            screen = QrConfig.SCREEN_SENSOR;
        } else if (rb_screen_sx.isChecked()) {
            screen = QrConfig.SCREEN_PORTRAIT;
        } else if (rb_screen_hx.isChecked()) {
            screen = QrConfig.SCREEN_LANDSCAPE;
        }

        if (rb_scanline_radar.isChecked()) {
            line_style = ScanLineView.style_radar;
        } else if (rb_scanline_grid.isChecked()) {
            line_style = ScanLineView.style_gridding;
        } else if (rb_scanline_hybrid.isChecked()) {
            line_style = ScanLineView.style_hybrid;
        } else if (rb_scanline_line.isChecked()) {
            line_style = ScanLineView.style_line;
        }


        QrConfig qrConfig = new QrConfig.Builder()
                .setDesText(et_qr_des.getText().toString())//扫描框下文字
                .setShowDes(cd_show_des.isChecked())//是否显示扫描框下面文字
                .setShowLight(cb_show_flash.isChecked())//显示手电筒按钮
                .setShowTitle(cb_show_title.isChecked())//显示Title
                .setShowAlbum(cb_show_album.isChecked())//显示从相册选择按钮
                .setNeedCrop(cb_crop_image.isChecked())//是否从相册选择后裁剪图片
                .setCornerColor(Color.parseColor("#E42E30"))//设置扫描框颜色
                .setLineColor(Color.parseColor("#E42E30"))//设置扫描线颜色
                .setLineSpeed(QrConfig.LINE_MEDIUM)//设置扫描线速度
                .setScanType(scan_type)//设置扫码类型（二维码，条形码，全部，自定义，默认为二维码）
                .setScanViewType(scan_view_type)//设置扫描框类型（二维码还是条形码，默认为二维码）
                .setCustombarcodeformat(QrConfig.BARCODE_PDF417)//此项只有在扫码类型为TYPE_CUSTOM时才有效
                .setPlaySound(cb_show_ding.isChecked())//是否扫描成功后bi~的声音
                .setDingPath(cb_show_custom_ding.isChecked() ? R.raw.test : R.raw.qrcode)//设置提示音(不设置为默认的Ding~)
                .setIsOnlyCenter(cb_only_center.isChecked())//是否只识别框中内容(默认为全屏识别)
                .setTitleText(et_qr_title.getText().toString())//设置Tilte文字
                .setTitleBackgroudColor(Color.parseColor("#262020"))//设置状态栏颜色
                .setTitleTextColor(Color.WHITE)//设置Title文字颜色
                .setShowZoom(cb_show_zoom.isChecked())//是否开始滑块的缩放
                .setAutoZoom(cb_auto_zoom.isChecked())//是否开启自动缩放(实验性功能，不建议使用)
                .setFingerZoom(cb_finger_zoom.isChecked())//是否开始双指缩放
                .setDoubleEngine(cb_double_engine.isChecked())//是否开启双引擎识别(仅对识别二维码有效，并且开启后只识别框内功能将失效)
                .setScreenOrientation(screen)//设置屏幕方式
                .setOpenAlbumText("选择要识别的图片")//打开相册的文字
                .setLooperScan(cb_loop_scan.isChecked())//是否连续扫描二维码
                .setLooperWaitTime(Integer.parseInt(et_loop_scan_time.getText().toString()) * 1000)//连续扫描间隔时间
                .setScanLineStyle(line_style)//扫描线样式
                .setAutoLight(cb_auto_light.isChecked())//自动灯光
                .setShowVibrator(cb_have_vibrator.isChecked())//是否震动提醒
                .create();
        QrManager.getInstance().init(qrConfig).startScan(MainActivity_2.this, new QrManager.OnScanResultCallback() {
            @Override
            public void onScanSuccess(ScanResult result) {
                Log.e(TAG, "onScanSuccess: " + result);
                scan_result=result.getContent();
                editText.setText(result.getContent());
                initData();
                TableRowView.selectedStrings.clear();
                Toast.makeText(getApplicationContext(), "内容：" + result.getContent()
                        + "  类型：" + result.getType(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public String[] getsplitString(String st,String split){
        String[] strlist = st.split(split);
        return strlist;
    }






    @Override
    protected void onStart() {
        super.onStart();
        Log.e("activityState","SecondActivity_onStart");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e("activityState","SecondActivity_onRestart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("activityState","SecondActivity_onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("activityState","SecondActivity_onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("activityState","SecondActivity_onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TableRowView.selectedStrings.clear();
    }
}



